<template>
  <div class="va-container">
    <div class="header">
      <h2>志愿者管理</h2>
      <div class="actions">
        <button class="primary-button" @click="navigateToCreateVA">添加招募任务</button>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      数据加载中...
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error">
      {{ error }}
    </div>
    
    <!-- 数据展示 -->
    <div v-else class="content">
      <div v-if="activities.length === 0" class="no-data">
        暂无志愿者活动信息
      </div>
      
      <div v-else>
        <div class="activities-list">
          <div 
            v-for="activity in paginatedActivities" 
            :key="activity.activityId" 
            class="activity-card"
          >
            <h3>{{ activity.title }}</h3>
            <div class="activity-info">
              <p><strong>活动ID:</strong> {{ activity.activityId }}</p>
              <p><strong>描述:</strong> {{ activity.description }}</p>
              <p><strong>地点:</strong> {{ activity.location }}</p>
              <p><strong>招募人数:</strong> {{ activity.recruitNum }}人</p>
              <p><strong>已招募人数:</strong> {{ activity.recruitedNum }}人</p>
              <p><strong>开始时间:</strong> {{ formatDate(activity.startTime) }}</p>
              <p><strong>结束时间:</strong> {{ formatDate(activity.endTime) }}</p>
              <p><strong>发布时间:</strong> {{ formatDate(activity.publishTime) }}</p>
              <p><strong>备注:</strong> {{ activity.remark }}</p>
            </div>
            <div class="activity-actions">
              <button class="modify-button" @click="modifyActivity(activity)">修改信息</button>
              <button class="manage-button" @click="manageEnrollments(activity.activityId)">报名管理</button>
              <button class="delete-button" @click="deleteActivity(activity.activityId)">删除招募</button>
            </div>
          </div>
        </div>
        
        <!-- 分页控件 -->
        <div class="pagination" v-if="totalPages > 1">
          <button 
            :disabled="currentPage === 1" 
            @click="changePage(currentPage - 1)"
            class="page-button"
          >
            上一页
          </button>
          
          <span class="page-info">
            第 {{ currentPage }} 页，共 {{ totalPages }} 页
          </span>
          
          <button 
            :disabled="currentPage === totalPages" 
            @click="changePage(currentPage + 1)"
            class="page-button"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'

// 定义活动数据结构
interface Activity {
  activityId: number
  title: string
  description: string
  startTime: string
  endTime: string
  location: string
  recruitNum: number
  recruitedNum: number
  status: number
  publishTime: string
  publisherId: number
  remark: string
}

// 定义 emit 事件
const emit = defineEmits(['navigate-to-create-va', 'edit-activity', 'manage-enrollments'])

// 响应式数据
const activities = ref<Activity[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const currentPage = ref(1)
const pageSize = ref(4) // 每页显示4条数据

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(activities.value.length / pageSize.value)
})

// 计算当前页的数据
const paginatedActivities = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return activities.value.slice(startIndex, endIndex)
})

// 获取志愿者活动信息
const fetchActivities = async () => {
  try {
    loading.value = true
    const token = localStorage.getItem('token')
    
    const response = await fetch('http://localhost:8080/va/my', {
      method: 'GET',
      headers: {
        'token': token || ''
      }
    })
    
    const result = await response.json()
    
    if (result.success) {
      activities.value = result.activities
      error.value = null
    } else {
      throw new Error('获取数据失败')
    }
  } catch (err) {
    console.error('获取志愿者活动信息失败:', err)
    error.value = '获取志愿者活动信息失败'
  } finally {
    loading.value = false
  }
}

// 格式化日期显示
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 导航到创建志愿者页面
const navigateToCreateVA = () => {
  emit('navigate-to-create-va')
}

// 修改活动信息
const modifyActivity = (activity: Activity) => {
  // 发出编辑活动事件，并传递活动数据
  emit('edit-activity', activity)
}

// 管理报名信息
const manageEnrollments = (activityId: number) => {
  // 发出管理报名信息事件，并传递活动ID
  emit('manage-enrollments', activityId)
}

// 删除活动
const deleteActivity = async (activityId: number) => {
  if (!confirm('确定要删除这个志愿者招募活动吗？')) {
    return
  }
  
  try {
    const token = localStorage.getItem('token')
    
    const response = await fetch(`http://localhost:8080/va/delete?activityId=${activityId}`, {
      method: 'DELETE',
      headers: {
        'token': token || ''
      }
    })
    
    const result = await response.json()
    
    if (result.success) {
      // 从列表中移除已删除的活动
      activities.value = activities.value.filter(activity => activity.activityId !== activityId)
      alert('删除成功')
    } else {
      throw new Error(result.message || '删除失败')
    }
  } catch (err) {
    console.error('删除活动失败:', err)
    alert('删除活动失败: ' + (err instanceof Error ? err.message : '未知错误'))
  }
}

// 页面切换函数
const changePage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchActivities()
})
</script>

<style scoped>
.va-container {
  padding: 20px;
  background: none;
  border: none;
  box-shadow: none;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: none;
  border: none;
  box-shadow: none;
  padding: 0;
}

.header h2 {
  color: #333;
  margin: 0;
}

.actions {
  display: flex;
  gap: 10px;
}

.primary-button {
  background: linear-gradient(to right, #66BB6A, #43A047);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.primary-button:hover {
  background: linear-gradient(to right, #5BAE5F, #3D8F3F);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.loading, .error, .no-data {
  text-align: center;
  padding: 40px 20px;
  font-size: 18px;
}

.error {
  color: #e74c3c;
}

.no-data {
  color: #7f8c8d;
}

.content {
  background: none;
  border: none;
  box-shadow: none;
  padding: 0;
}

.activities-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  background: none;
  border: none;
  box-shadow: none;
  padding: 0;
}

.activity-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  border-left: 5px solid #66BB6A;
}

.activity-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

.activity-card h3 {
  color: #66BB6A;
  margin-top: 0;
  border-bottom: 2px solid #eee;
  padding-bottom: 10px;
}

.activity-info p {
  margin: 8px 0;
  color: #555;
}

.activity-actions {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.modify-button {
  background: linear-gradient(to right, #3498db, #2980b9);
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.modify-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.delete-button {
  background: linear-gradient(to right, #e74c3c, #c0392b);
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.delete-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.manage-button {
  background: linear-gradient(to right, #9b59b6, #8e44ad);
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.manage-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
  background: none;
  border: none;
  box-shadow: none;
  padding: 0;
}

.page-button {
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-button:hover:not(:disabled) {
  background: #2980b9;
  transform: translateY(-2px);
}

.page-button:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.page-info {
  color: #333;
  font-weight: bold;
}
</style>